package com.caidan.search.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolExecutorConfig {

    // 会员线程池
    @Bean(name = "memberThreadPool")
    public ThreadPoolExecutor getMemberThreadPoolExecutor() {
        return new ThreadPoolExecutor(
                8,  // corePoolSize
                16, // maximumPoolSize
                3, TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(1000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(@NotNull Runnable runnable) {
                        Thread thread = new Thread(runnable);
                        thread.setName("member-thread-" + ThreadLocalRandom.current().nextInt(10000));
                        return thread;
                    }
                });
    }

    // 普通用户线程池
    @Bean(name = "userThreadPool")
    public ThreadPoolExecutor getUserThreadPoolExecutor() {
        return new ThreadPoolExecutor(
                4,  // corePoolSize, 设置为较小的线程池
                8,  // maximumPoolSize
                3, TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(1000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(@NotNull Runnable runnable) {
                        Thread thread = new Thread(runnable);
                        thread.setName("user-thread-" + ThreadLocalRandom.current().nextInt(10000));
                        return thread;
                    }
                });
    }

    // 任务调度策略：如果普通用户队列较少，将任务移交给会员线程池
    public void adjustThreadPoolPriority(ThreadPoolExecutor memberThreadPool, ThreadPoolExecutor userThreadPool) {
        // 判断普通用户线程池队列大小
        if (userThreadPool.getQueue().size() < 100) {
            // 如果普通用户任务队列较少，将其任务交给会员线程池处理
            transferTasksToMemberPool(memberThreadPool, userThreadPool);
        }
    }

    // 转移任务的方法：模拟将任务从普通用户线程池转移到会员线程池
    private void transferTasksToMemberPool(ThreadPoolExecutor memberThreadPool, ThreadPoolExecutor userThreadPool) {
        // 假设我们有一些普通用户任务在队列中
        for (Runnable task : userThreadPool.getQueue()) {
            memberThreadPool.execute(task); // 将任务交给会员线程池执行
        }
        userThreadPool.getQueue().clear(); // 清空普通用户队列
    }
}
